//
//  KZMakeExamVC.m
//  lg_zhinengbeikao_english
//
//  Created by 朱凯 on 2018/12/26.
//  Copyright © 2018 zhukai. All rights reserved.
//

#import "KZMakeExamVC.h"


// view
#import "KZExamProgressView.h"  // 进度条
#import "KZExamItemView.h"      // 试卷
#import "KZTimerView.h"         // 计时器


// test
#import "KZMenuView.h"

@interface KZMakeExamVC () <UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableDictionary<NSString *, KZExamItemView *> *itemViews;

@property (nonatomic, strong) KZExamProgressView *progressView;
@property (nonatomic, strong) KZTimerView *timerView;
@property (nonatomic, strong) UIScrollView *scroll;

@end

@implementation KZMakeExamVC
{
    NSInteger _maxCount;        // 最大题数
    NSMutableArray *_items;
    NSInteger _currentIndex;    // 当前显示的题目索引
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNaviUI];
    [self setupUI];
}

#pragma mark - 创建视图
- (void)setupNaviUI {
    
    [self addLeftBackBarButtonItem];
    
    _timerView = [[KZTimerView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [_timerView setOnTimerStatusChanged:^(BOOL pausing) {
        NSLog(@"%@", pausing?@"暂停":@"恢复");
    }];
    [_timerView start:100 * 60 - 5];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = FONT(14);
    button.frame = CGRectMake(0, 0, 60, 30);
    [button setTitle:@"选择" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onSelectIndex) forControlEvents:UIControlEventTouchUpInside];
    
    [self addNaviItemWithCustomViews:@[_timerView, button] position:KZNavigationItemPositionModeRight];
}

- (void)setupUI {
    
    _progressView = [KZExamProgressView new];
    _progressView.totalIndex = 20;
    _progressView.index = 10;
    
    
    [self.view addSubview:_progressView];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.equalTo(self.view);
        make.height.mas_equalTo(5);
    }];
    
    _scroll = [UIScrollView new];
    _scroll.delegate = self;
    _scroll.pagingEnabled = true;
    [self.view addSubview:_scroll];
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(5, 0, 0, 0)).priorityMedium();
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(0);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        }
    }];
    
    [self.view layoutIfNeeded];
    
    _items = [NSMutableArray new];
    NSInteger index = 0;
    for (int i = 0; i < 10; i ++) {
        NSMutableArray *temp = [NSMutableArray new];
        for (int k = 0; k < 3; k ++) {
            [temp addObject:@(index)];
            index ++;
        }
        [_items addObject:temp];
    }
    _maxCount = _items.count;
    _currentIndex = 0;
    _itemViews = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < 2; i ++) {
        KZExamItemView *view = [[KZExamItemView alloc] init];
        view.frame = CGRectMake(i * _scroll.width, 0, _scroll.width, _scroll.height);
        view.index = i;
        view.itemNumbers = _items[i];
        [_scroll addSubview:view];
        _itemViews[[NSString stringWithFormat:@"%i", i]] = view;
    }

    _scroll.contentSize = CGSizeMake(self.view.width * _maxCount, 0);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    scrollView.scrollEnabled = false;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    NSInteger index = (NSInteger)(scrollView.contentOffset.x / scrollView.width);
    if (index == _currentIndex) {
        scrollView.scrollEnabled = true;
        return;
    } else {
        NSInteger number = index > _currentIndex ? NSIntegerMax : -NSIntegerMax;
        _currentIndex = index;
        
        [self pushToExamItemAtIndex:_currentIndex seekTo:number];
    }
    
    
}


- (void)onSelectIndex {
    
    KZMenuView *view = [KZMenuView new];
    NSMutableArray *temp = [NSMutableArray new];
    for (int i = 0; i < 30; i ++) {
        KZMenuViewItem *item = [KZMenuViewItem new];
        item.title = [NSString stringWithFormat:@"%i", i];
        [temp addObject:item];
    }
    view.menuItems = temp.copy;
    view.itemClickBlock = ^(NSInteger index) {
        [self pushToExamItemAtIndex:index / 3 seekTo:index];
    };
    [view showAtPoint:CGPointMake(SCREEN_WIDTH - 80, 0) inView:self.view];
}

- (void)pushToExamItemAtIndex:(NSInteger)index seekTo:(NSInteger)number {
    
    // 快捷取值
    CGFloat w = _scroll.width;
    CGFloat h = _scroll.height;
    
    // 选择快进到某题前的可视视图，可视视图会在创建完
    UIView *currentVisableView = _itemViews[[NSString stringWithFormat:@"%li", _currentIndex]];
    
    // 先把两侧的视图移除掉，仅保留现在可视的视图，用于滚动
    for (KZExamItemView *view in self.itemViews.allValues) {
        if (view != currentVisableView) {
            [view removeFromSuperview];
        }
    }
    
    // 记录当前要滑动到的位置的视图的引用
    KZExamItemView *indexView = nil;
    // 如果还未创建过，则创建
    if (_itemViews[[NSString stringWithFormat:@"%li", index]] == nil) {
        
        indexView = [KZExamItemView new];
        indexView.index = index;
        indexView.itemNumbers = _items[index];
        [_scroll addSubview:indexView];
        _itemViews[[NSString stringWithFormat:@"%li", index]] = indexView;
    }
    // 存在则直接获取
    else {
        indexView = _itemViews[[NSString stringWithFormat:@"%li", index]];
        [_scroll addSubview:indexView];
    }
    // 设置frame，放到对应索引的位置去
    indexView.frame = CGRectMake(index * w, 0, w, h);
    // 添加到scroll上
    
    // 如果点击试题快速跳转到某一题时，要假装从当前可视的视图滚动到目标视图，因此需要移动currentVisableView的位置并改变contentOffset，这样看起来就好像没有移动一样
    if (index == _currentIndex) {}
    else if (index > _currentIndex) {
        
        currentVisableView.frame = CGRectMake(indexView.left - w, 0, w, h);
        _scroll.contentOffset = CGPointMake((index - 1) * w, 0);
        
    } else {
        
        currentVisableView.frame = CGRectMake(indexView.right, 0, w, h);
        _scroll.contentOffset = CGPointMake((index + 1) * w, 0);
    }
    
    // 滚动动画：从当前可视的视图滚动到目标视图，index == _currentIndex是不需要滚动，时间设为0即可
    [UIView animateWithDuration:index == _currentIndex ? 0 : 0.35 animations:^{
        
        self.scroll.contentOffset = CGPointMake(index * w, 0);
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            
            if (index == self->_currentIndex) {
                if (number > 100000) {
//                    [indexView seekToFirst];
                } else if (number < -100000) {
//                    [indexView seekToLast];
                } else {
                    [indexView seekToNumber:number];
                }
            } else {
                [indexView seekToNumber:number];
            }
            
            // 如果可视视图不是目标视图，则需要移除可视视图
            if (index != self->_currentIndex) {
                [currentVisableView removeFromSuperview];
            }
            
            // 目标视图的下一题索引和上一题序索引
            NSInteger nextIndex = index + 1;
            NSInteger prevIndex = index - 1;
            
            // 目标视图不是最后一题，则需要创建下一题
            if (nextIndex < self->_maxCount) {
                
                KZExamItemView *nextView = nil;
                if (self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]] == nil) {
                    
                    nextView = [KZExamItemView new];
                    nextView.index = nextIndex;
                    nextView.itemNumbers = self->_items[nextIndex];
                    [self.scroll addSubview:nextView];
                    self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]] = nextView;
                }
                else {
                    nextView = self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]];
                    [self.scroll addSubview:nextView];
                }
                nextView.frame = CGRectMake(indexView.right, 0, w, h);
            }
            
            // 目标视图不是第一题，则需要创建上一题
            if (prevIndex >= 0) {

                KZExamItemView *prevView = nil;
                if (self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]] == nil) {
                    
                    prevView = [KZExamItemView new];
                    prevView.index = prevIndex;
                    prevView.itemNumbers = self->_items[prevIndex];
                    [self.scroll addSubview:prevView];
                    self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]] = prevView;
                }
                else {
                    prevView = self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]];
                    [self.scroll addSubview:prevView];
                }
                prevView.frame = CGRectMake(indexView.left - w, 0, w, h);
            }
        }
        
        // 视图全部设置完毕，可滑动
        self.scroll.scrollEnabled = true;
        // 修改当前可视视图的索引
        self->_currentIndex = index;
    }];
}
@end
